<template>
  <div class="oe-exam-word clearfix">
    <info-top :showExpend="false"></info-top>
    <div style="padding: 20px;padding-bottom: 0px;">
      <top-tip :title="titleList" :batchid="batchid" :goManage="true"></top-tip>
    </div>
    <div class="oe-exam-list fl">
      <h1>{{question.title}}</h1>
      <div class="oe-exam-info">
        <span v-if="courseShow">课程：{{course}}</span>
        <span v-if="timeShow">答卷时间{{time}}分钟</span>
        <span v-if="gradeShow">答卷满分：{{grade}}分</span>
      </div>
      <div style="word-break:break-all;text-align: left;line-height:26px;font-size: 16px;margin-bottom: 10px;" v-if="remarkShow">考试要求：{{remark || '暂无要求'}}</div>
      <div class="oe-exam-question" v-for="(item,index) in question.choice" :key="index">
        <div class="oe-question-title">
          {{item.num}}、
          <span>（{{item.QuestionType}}）</span>
          <span v-html="item.Title"></span>({{item.Score}}分)  （&nbsp;&nbsp;&nbsp;&nbsp;）
        </div>
        <div style="margin-left: 38px;line-height: 34px;" v-for="(AnswerList,key) in item.AnswerList" :key="key">{{AnswerList.Content}}</div>
      </div>
      <div class="oe-exam-question" v-for="(item,index) in question.fill" :key="index">
        <div class="oe-question-title">
          {{item.num}}、
          <span>（{{item.QuestionType}}）</span>
          <span v-html="item.Title"></span>({{item.Score}}分)
        </div>
        <div style="margin-left: 38px;line-height: 34px;" v-for="(AnswerList,key) in item.AnswerList" :key="key">{{AnswerList.Content}}_______________</div>
      </div>
      <div class="oe-exam-question" v-for="(item,index) in question.quesAnswer" :key="index">
        <div class="oe-question-title">
          {{item.num}}、
          <span>（{{item.QuestionType}}）</span>
          <span v-html="item.Title"></span>({{item.Score}}分)
        </div>
        <div style="height: 150px;"></div>
      </div>
      <div class="oe-exam-question" v-for="(item,index) in question.matching" :key="index">
        <div class="oe-question-title">
          {{item.num}}、
          <span>（{{item.QuestionType}}）</span>
          <span v-html="item.Title"></span>({{item.Score}}分)
        </div>
        <div style="margin-left: 38px;line-height: 34px;" v-for="(aAnswer,key) in item.aAnswer" :key="key">{{aAnswer.Content}}（&nbsp;&nbsp;&nbsp;&nbsp;）</div>
        <div style="margin-left: 38px;line-height: 34px;" v-for="(pAnswer,key) in item.pAnswer" :key="key">{{pAnswer.Content}}</div>
      </div>
      <div class="oe-exam-question" v-for="(item,index) in question.child" :key="index">
        <div class="oe-question-title">
          {{item.num}}、
          <span>（{{item.QuestionType}}）</span>
          <span v-html="item.Title"></span>({{item.Score}}分)
        </div>
        <div style="margin-left: 38px;line-height: 34px;" v-for="(child,key) in item.option" :key="key">
          <div class="oe-question-title">
            {{child.num}}、
            <span>（{{child.QuestionType}}）</span>
            <span v-html="child.Title"></span>({{child.Score}}分)  （&nbsp;&nbsp;&nbsp;&nbsp;）
          </div>
          <div style="margin-left: 38px;line-height: 34px;" v-for="(AnswerList,key) in child.AnswerList" :key="key">{{AnswerList.Content}}</div>
        </div>
      </div>
    </div>
    <div class="set-exam-info fr">
      <div class="set-exam-title">试卷配置</div>
      <div class="set-exam-collocate">
        <div class="oe-collocate-item">
          <span class="oe-item-label">试卷名称:</span>
          <a-input class="oe-item-input" v-model="question.title" />
        </div>
        <div class="oe-collocate-item">
          <a-checkbox class="oe-item-label" :value="remarkShow" default-checked @change="onRemarkShow">考试要求:</a-checkbox>
          <a-textarea class="oe-item-input" v-model="remark" placeholder="输入考试要求" maxLength="220" auto-size />
        </div>
        <div class="oe-collocate-item">
          <a-checkbox class="oe-item-label" :value="courseShow" default-checked @change="onCourseShow">课程:</a-checkbox>
          <a-input class="oe-item-input" v-model="course" placeholder="输入课程" />
        </div>
        <div class="oe-collocate-item">
          <a-checkbox class="oe-item-label" :value="timeShow" default-checked @change="onTimeShow">考试时长:</a-checkbox>
          <a-input-number class="oe-item-input" v-model="time" :min="0"/>
        </div>
        <div class="oe-collocate-item">
          <a-checkbox class="oe-item-label" :value="gradeShow" default-checked @change="onGradeShow">试卷总分:</a-checkbox>
          <a-input-number class="oe-item-input" disabled v-model="grade" :min="0"/>
        </div>
      </div>
      <a-button type="primary" @click="exportWord">试卷Word导出</a-button>
      <a-tooltip placement="bottomRight">
        <template slot="title">
          <span>导出的word文档不显示图片和上传的文件无法导出显示，需自行手动添加。</span>
        </template>
        <a-icon style="margin-left: 10px;font-size:20px;color: #f00;" type="question-circle" />
      </a-tooltip>
    </div>
  </div>
</template>

<script>
import Docxtemplater from 'docxtemplater';
import PizZip from 'pizzip';
import JSZipUtils from 'jszip-utils';
import { saveAs } from 'file-saver';
import infoTop from '@/components/info-top/index.vue';
import topTip from '@/components/top-tip/index.vue';
export default {
  components: {
    infoTop,
    topTip
  },
  data() {
    return {
      titleList: [
              { text: '批次管理(考试)管理' },
              { text: '预览试卷' },
              { text: '导出试卷', color: '#0177D5' }
            ],
      title: "考试试卷",
      examData: {},
      Alphabet: [
        "A",
        "B",
        "C",
        "D",
        "E",
        "F",
        "G",
        "H",
        "I",
        "J",
        "K",
        "L",
        "M",
        "N",
        "O",
        "P",
        "Q",
        "R",
        "S",
        "T",
        "U",
        "V",
        "W",
        "X",
        "Y",
        "Z"
      ],
      question: {
        title: "",
        course: "",
        time: "",
        grade: 0,
        remark: "",
        choice: [],
        fill: [],
        quesAnswer: [],
        matching: [],
        child: [],
        quesNum: [
          {Content: '一'},
          {Content: '二'},
          {Content: '三'},
          {Content: '四'},
        ]
      },
      remark: '',
      remarkShow: true,
      course: '课程名称',
      courseShow: true,
      time: 90,
      timeShow: true,
      grade: 0,
      gradeShow: true,
      choice: [],
      fill: [],
      quesAnswer: [],
      matching: [],
      child: []
    };
  },
  props: {
    examId: {
      type: String,
      default: ''
    },
    batchid: {
      type: String,
      default: ''
    }
  },
  mounted() {
    this.onLineExamPreview();
  },
  methods: {
    // 获取考试数据
    onLineExamPreview() {
      this.$http
        .post('/api/design/marking/onLineExamPreview', {
          examId: this.examId
        })
        .then((rst) => {
          if (rst.code > 0) {
            this.examData = rst;
            this.question.title = rst.title;
            this.grade = rst.totalScore;
            this.remark = rst.remark;
            this.setData();
          } else {
            this.$message.error(rst.msg);
          }
         })
    },
    // 是否要显示考试要求
    onRemarkShow(e) {
      this.remarkShow = e.target.checked;
    },
    // 是否要显示课程
    onCourseShow(e) {
      this.courseShow = e.target.checked;
    },
    // 是否要显示时长
    onTimeShow(e) {
      this.timeShow = e.target.checked;
    },
    // 是否要显示总分
    onGradeShow(e) {
      this.gradeShow = e.target.checked;
    },
    // 导出前数据处理
    setData() {
      var list = this.examData.list;
      for (let i = 0; i < list.length; i++) {
        if (list[i].QuestionType == 1 || list[i].QuestionType == 2 || list[i].QuestionType == 3) {
          this.choice.push(list[i]);
        } else if(list[i].QuestionType == 5) {
            this.fill.push(list[i]);
        } else if(list[i].QuestionType == 6) {
            this.quesAnswer.push(list[i]);
        } else if(list[i].QuestionType == 7) {
            this.matching.push(list[i]);
        } else if(list[i].QuestionType == 8 || list[i].QuestionType == 9 || list[i].QuestionType == 11) {
            this.child.push(list[i]);
        } 
      }
      this.setChoiceData()
    },
    //单选 多选 判断
    setChoiceData() {
      var list = this.choice;
      for (let i = 0; i < list.length; i++) {
        var lisData = {
          num: 0,
          Score: 0,
          QuestionType: "",
          Title: "",
          AnswerList: []
        };
        lisData.num = i + 1;
        lisData.Score = list[i].Score;
        if (list[i].QuestionType == 1) {
          lisData.QuestionType = "单选题";
        } else if (list[i].QuestionType == 2) {
          lisData.QuestionType = "多选题";
        } else if (list[i].QuestionType == 3) {
          lisData.QuestionType = "判断题";
        }
        lisData.Title = list[i].Title.replace(/<[^>]+>/g, "");
        if (list[i].QuestionType == 1 || list[i].QuestionType == 2) {
          for (let key = 0; key < list[i].AnswerList.length; key++) {
            let answer = {
              Content: ""
            };
            answer.Content = this.Alphabet[key] + "、" + list[i].AnswerList[key].Content.replace(/<[^>]+>/g, "");
            lisData.AnswerList.push(answer);
          }
        } else if (list[i].QuestionType == 3) {
          let answer = {
            Content: ""
          };
          lisData.AnswerList = [{ Content: "A、正确" }, { Content: "B、错误" }];
        }
        this.question.choice.push(lisData);
      }
      this.setFillData();
    },
    // 填空题
    setFillData() {
       var list = this.fill;
       for (let i = 0; i < list.length; i++) {
           var lisData = {
              num: 0,
              Score: 0,
              QuestionType: "填空题",
              Title: "",
              AnswerList: []
           };
           lisData.num = this.choice.length + i + 1;
           lisData.Score = list[i].Score;
           lisData.Title = list[i].Title.replace(/<img[^>]+>/g, " ______ ");
           lisData.Title = lisData.Title.replace(/<[^>]+>/g, "");
           for (let key = 0; key < list[i].AnswerList.length; key++) {
               let answer = {
                Content: ""
               };
               answer.Content = key+1+'、';
               lisData.AnswerList.push(answer);
           }
           this.question.fill.push(lisData);
       }
       this.setQuesAnswerData(); 
    },
    // 问答题
    setQuesAnswerData() {
       var list = this.quesAnswer;
       for (let i = 0; i < list.length; i++) {
           var lisData = {
              num: 0,
              Score: 0,
              QuestionType: "问答题",
              Title: "",
           };
           lisData.num = this.choice.length + this.fill.length + i + 1;
           lisData.Score = list[i].Score;
           lisData.Title = list[i].Title.replace(/<[^>]+>/g, "");
           this.question.quesAnswer.push(lisData);
       }
       this.setMatchingData(); 
    },
    // 匹配题
    setMatchingData() {
       var list = this.matching;
       for (let i = 0; i < list.length; i++) {
           var lisData = {
              num: 0,
              Score: 0,
              QuestionType: "匹配题",
              Title: "",
              aAnswer: [],
              pAnswer: [],
           };
           lisData.num = this.choice.length + this.fill.length + this.quesAnswer.length + i + 1;
           lisData.Score = list[i].Score;
           lisData.Title = list[i].Title.replace(/<[^>]+>/g, "");
           for (let key = 0; key < list[i].AnswerList.length; key++) {
              let answer = {
                Content: ""
              };
              answer.Content = key+1 + "、" + list[i].AnswerList[key].OptionContent.replace(/<[^>]+>/g, "");
              lisData.aAnswer.push(answer);
           }
           for (let key = 0; key < list[i].PiAnswer.length; key++) {
              let answer = {
                Content: ""
              };
              answer.Content = this.Alphabet[key] + "、" + list[i].PiAnswer[key].OptionAnswerContent.replace(/<[^>]+>/g, "");
              lisData.pAnswer.push(answer);
           }
           this.question.matching.push(lisData);
       }
       this.setChildData(); 
    },
    // 含有子题目
    // 问答题
    setChildData() {
       var list = this.child;
       for (let i = 0; i < list.length; i++) {
           var lisData = {
              num: 0,
              Score: 0,
              QuestionType: "",
              Title: "",
              option: []
           };
           lisData.num = this.choice.length + this.fill.length + this.quesAnswer.length + this.matching.length + i + 1;
           lisData.Score = list[i].Score;
           if (list[i].QuestionType == 8) {
              lisData.QuestionType = "阅读理解";
           } else if (list[i].QuestionType == 9) {
              lisData.QuestionType = "完形填空";
           } else if (list[i].QuestionType == 11) {
              lisData.QuestionType = "视听题";
           }
           lisData.Title = list[i].Title.replace(/<[^>]+>/g, "");
           for (let key = 0; key < list[i].SubQuesList.length; key++) {
              var childData = {
                  num: 0,
                  Score: 0,
                  QuestionType: "",
                  Title: "",
                  AnswerList: []
              };
              childData.num = key + 1;
              childData.Score = list[i].SubQuesList[key].Score;
              if (list[i].SubQuesList[key].SubQuestionType == 1) {
                childData.QuestionType = "单选题";
              } else if (list[i].SubQuesList[key].SubQuestionType == 2) {
                childData.QuestionType = "多选题";
              } else if (list[i].SubQuesList[key].SubQuestionType == 3) {
                childData.QuestionType = "判断题";
              }
              childData.Title = list[i].SubQuesList[key].Title.replace(/<[^>]+>/g, "");
              if (list[i].SubQuesList[key].SubQuestionType == 1 || list[i].SubQuesList[key].SubQuestionType == 2) {
                for (let keyNum = 0; keyNum < list[i].SubQuesList[key].AnswerList.length; keyNum++) {
                    let answer = {
                        Content: ""
                    };
                    answer.Content = this.Alphabet[keyNum] + "、" + list[i].SubQuesList[key].AnswerList[keyNum].Content.replace(/<[^>]+>/g, "");
                    childData.AnswerList.push(answer);
                }
              } else if (list[i].SubQuesList[key].SubQuestionType == 3) {
                let answer = {
                    Content: ""
                };
                childData.AnswerList = [{ Content: "A、正确" }, { Content: "B、错误" }];
              }
              lisData.option.push(childData);
           }
           this.question.child.push(lisData);
       } 
       console.log(this.question);
    },
    // 点击导出word
    exportWord() {
      this.question.course = '';
      if (this.courseShow) {
        this.question.course = this.question.course + '课程：' + this.course;
      }
      this.question.time = '';
      if (this.timeShow) {
        this.question.time = this.question.time + '答卷时间' + this.time + '分钟';
      }
      this.question.grade = '';
      if (this.gradeShow) {
        this.question.grade = this.question.grade + '答卷满分：' + this.grade + '分';
      }
      if (this.remark == '') {
        this.remark = '暂无要求'
      }
      if (this.remarkShow) {
        this.question.remark = '考试要求：' + this.remark;
      } else {
        this.question.remark = '';
      }
      const that = this;
      // 读取并获得模板文件的二进制内容
      JSZipUtils.getBinaryContent('../../exam.docx', function(error, content) {
        // gy-agree-service.docx是模板。我们在导出的时候，会根据此模板来导出对应的数据
        // 抛出异常
        if (error) {
          throw error;
        }
        console.log(content);
        // 创建一个PizZip实例，内容为模板的内容
        const zip = new PizZip(content);
        // 创建并加载docxtemplater实例对象
        const doc = new Docxtemplater().loadZip(zip);
        // 设置模板变量的值
        doc.setData({
          ...that.question
        });
        try {
          // 用模板变量的值替换所有模板变量
          doc.render();
        } catch (error) {
          // 抛出异常
          const e = {
            message: error.message,
            name: error.name,
            stack: error.stack,
            properties: error.properties
          };
          console.log(JSON.stringify({ error: e }));
          throw error;
        }

        // 生成一个代表docxtemplater对象的zip文件（不是一个真实的文件，而是在内存中的表示）
        const out = doc.getZip().generate({
          type: 'blob',
          mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
        });
        // 将目标文件对象保存为目标类型的文件，并命名
        saveAs(out, that.question.title);
      });
    }
  }
};
</script>

<style>
</style>